#!/bin/bash
# 操作方式
# ./build.sh 
die() {
	echo -e "\033[31m ERROR: $@ \033[0m"
	exit 1
}

log() {
    echo -e "\033[32m LOG: $@ \033[0m"
}

# 首先进入文件所在目录
cd $(dirname "$0")

local_path=`pwd`

# 项目名称
project_name=app

# 编译目录
build_dir=${local_path}/build

# 可执行文件输出目录
out_dir=${local_path}/out

# 是否需要清空 0:不删除 1:删除
clean_all_flag=0

# 获取参数输入
while getopts "c" opt
do
    case $opt in
        c)
            clean_all_flag=1
            ;;
        ?)
            ;;
    esac
done
#通过shift $(($OPTIND - 1))的处理，$*中就只保留了除去选项内容的参数，
#可以在后面的shell程序中进行处理
shift $(($OPTIND - 1))

# 判定是否clean
if [ ${clean_all_flag} -eq 1 ];then
    rm -rf ${build_dir} ${out_dir}
    log "clean Success."
fi

# 创建编译目录
if [ ! -d "${build_dir}" ]; then
  mkdir ${build_dir}
fi

# 生成编译脚本
cmake -B ${build_dir} -DTARGET_NAME=${project_name} -DBUILD_DIR=${build_dir} -DOUT_DIR=${out_dir}
if [ $? -ne 0 ]; then
    die "cmake is fail..."
fi
# 执行编译
make -C ${build_dir} -j4
if [ $? -ne 0 ]; then
    die "make is fail..."
fi
# 执行安装
make -C ${build_dir} install
if [ $? -ne 0 ]; then
    die "install is fail..."
fi

log "build Success."